import { computed, reactive, toRefs } from "vue";

export const useTable = (
  api: (params: any) => Promise<any>,
  initParam: object,
  pagination: boolean = true,
  dataCallBack?: (data: any) => any
) => {
  const state = reactive({
    tableDate: [], //表格数据
    pageable: {
      //分页数据
      page: 1, //当前页数
      size: 10, //每页显示条数
      total: 0, //总条数
    },

    // 总参数(包含分页和查询参数)
    totalParam: {},
  });

  /**
   * @description 分页查询参数(只包括分页和表格字段排序,其他排序方式可自行配置)
   * */
  const pageParam = computed({
    get: () => {
      return {
        page: state.pageable.page,
        size: state.pageable.size,
      };
    },
    set: (newVal: any) => {
      console.log("我是分页更新之后的值", newVal);
    },
  });

  /**
   * @description 获取表格数据
   * @return void
   * */
  const getTableList = async (type?: boolean) => {
 
    if (!api) return;
    try {
      // 先把初始化参数和分页参数放到总参数里面
      Object.assign(
        state.totalParam,
        initParam,
        pagination ? (type ? { page: 1, size: 10 } : pageParam.value) : {}
      );
      console.log("请求参数", initParam);
      let { data } = await api({
        ...state.totalParam,
      });
      // console.log('@@@',api());

      console.log("接口返回的数据", data);
      dataCallBack && dataCallBack(data); //获取数据的回调
      state.tableDate = pagination ? data.results : data;

      // 解构后台返回的分页数据 (如果有分页更新分页信息)
      if (pagination) {
        const { count } = data;
        state.pageable.total = count;
        // updatePageable({ pageNum, pageSize, total });
      }
    } catch (error) {
      console.log(error);
      //   requestError && requestError(error);
    }
  };

  /**
   * @description 每页条数改变
   * @param {Number} val 当前条数
   * @return void
   * */
  const currentChange = (val: number) => {
    console.log("每页条数改变", val);
    state.pageable.page = val;
    getTableList();
  };

  /**
   * @description 每页显示几条数发生改变
   */
  const sizeChange = (val: number) => {
    console.log("每页显示几条数发生改变", val);
    state.pageable.page = 1;
    state.pageable.size = val;
    getTableList();
  };

  return {
    ...toRefs(state),
    getTableList,
    currentChange,
    sizeChange,
  };
};
